package com;

import com.jumaojiang.constant.AppConfig;
import com.jumaojiang.mapper.*;
import com.jumaojiang.pojo.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Calendar.*;
import static java.util.Calendar.SECOND;

/**
 * javaee-course-private
 *
 * @author wuhanwei
 * @version 1.0
 * @date 2021/11/19
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class CreateDownloadFile {

    @Autowired
    private FileResourceMapper fileResourceMapper;
    @Autowired
    private VideoResourceMapper videoResourceMapper;
    @Autowired
    private ResourceGetTimeMapper resourceGetTimeMapper;
    @Autowired
    private RsVideoMapper rsVideoMapper;
    @Autowired
    private AppConfig appConfig;
    @Autowired
    private RsFileMapper rsFileMapper;
    @Autowired
    private FileUrlMapper fileUrlMapper;

    public static void main(String[] args) {
//        String str = "Spring Boot 章末总结";
//        str = str.trim().replaceAll(" ","_").replaceAll("\\(","_").replaceAll("\\)", "").replaceAll("&","和");
//        System.out.println(str);

        int[] ints = {};
        int[] temp = temp(ints);
        for (int i : temp) {
            System.out.print(i + " ");
        }
    }

    public static int[] temp(int[] digits){
        int index = digits.length - 1;
        for( ;index>=0;index-- ){
            if((digits[index] += 1) > 9){
                digits[index] = 0;
            }else{
                break;
            }
        }
        if(digits[0] == 0){
            int[] resArr = new int[digits.length + 1];
            resArr[0] = 1;
            return resArr;
        }
        return digits;
    }

    /**
     * 生成脚本文件
     */
    @Test
    public void createscriptFile(){
        List<Integer> queryChapterList = new ArrayList<>();
        for(int i=3; i<=17; i++){
            queryChapterList.add(i);
        }

        // true:生成视频 false:生成文件
        boolean videoOrFile = false;

        String[] chapterArr = {"第一章_课前导学", "第二章_JAVA基础", "第三章_面向对象", "第四章_核心类库", "第五章_数据库", "第六章_前端技术", "第七章_JAVAWEB", "第八章_WEB实训项目", "第九章_企业开发环境",
                "第十章_SSM", "第十一章_微服务与分布式", "第十二章_容器化", "第十三章_分布式架构解决方案", "第十四章_互联网高并发解决方案", "第十五章_分布式高并发实战项目",
                "第十六章_前沿生态", "第十七章_扩展提升"};

        if(videoOrFile){
            // TODO : 生成下载视频脚本
            // 创建文件
            String savePath = appConfig.getFileSavePath();
            String saveDirName = appConfig.getFileSaveDirName();
            System.out.println("savePath: " + savePath);
            System.out.println("saveDirName: " + saveDirName);
            String saveFileName = "new_chapter_";
            for (Integer integer : queryChapterList) {
                saveFileName += integer.toString()+"_";
            }
            saveFileName += ".sh";
            File dir = new File(savePath + File.separator + saveDirName);
            if( !dir.exists() ){
                dir.mkdirs();
            }
            File saveFile = new File(dir, saveFileName);
            if( !saveFile.exists() ){
                try {
                    saveFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            savePath = "/usr/local/baiduCloud";
            // 封装集合
            Map<String, Map<String, List<RsVideo>>> map = new HashMap<>();
            for (Integer chaId : queryChapterList) {
                // 添加章节Map
                Map<String, List<RsVideo>> chaMap = new HashMap<>();
                map.put(chapterArr[chaId-1], chaMap);
                List<String> strings = rsVideoMapper.querySection(chaId);
                // 小节编号
                int sectionNum = 2;
                for (String string : strings) {
                    // 章节Map里添加小节Map
                    List<RsVideo> secMap = new ArrayList<>();
                    String string2 = string.trim().replaceAll(" ", "_").replaceAll("\\(", "_").replaceAll("\\)", "").replaceAll("&", "和");
                    chaMap.put("第"+(sectionNum++)+"节_"+string2, secMap);
                    // 小节里查询video
                    RsVideoExample rsVideoExample = new RsVideoExample();
                    RsVideoExample.Criteria criteria = rsVideoExample.createCriteria();
                    criteria.andChaIdEqualTo(chaId);
                    criteria.andSectionTitleEqualTo(string);
                    List<RsVideo> rsVideos = rsVideoMapper.selectByExample(rsVideoExample);
                    // 处理名称空格,括号
                    for (RsVideo rsVideo : rsVideos) {
                        rsVideo.setVideoName(rsVideo.getVideoName().trim().replaceAll(" ","_").replaceAll("\\(","_").replaceAll("\\)", "").replaceAll("&","和"));
                    }
                    // video排序
                    Stream<RsVideo> sorted = rsVideos.stream().sorted((o1, o2) -> {
                        String[] split1 = o1.getVideoUrl().split("/");
                        String s1 = split1[split1.length - 1];
                        String[] split2 = o2.getVideoUrl().split("/");
                        String s2 = split2[split2.length - 1];
                        int i1, i2;
                        try {
                            i1 = Integer.parseInt(s1);
                            i2 = Integer.parseInt(s2);
                        } catch (NumberFormatException e) {
                            return -1;
                        }
                        return i1 - i2;
                    });
                    List<RsVideo> collectRsVideos = sorted.collect(Collectors.toList());
                    // 添加到小节Map
                    secMap.addAll(collectRsVideos);
                }
            }

            // 创建输出流
            String content = null;
            FileOutputStream fileOutputStream = null;
            PrintStream ps = null;
            try {
                fileOutputStream = new FileOutputStream(saveFile);
                ps = new PrintStream(fileOutputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 遍历集合
            Set<Map.Entry<String, Map<String, List<RsVideo>>>> chapterEntry = map.entrySet();
            for (Map.Entry<String, Map<String, List<RsVideo>>> chapter : chapterEntry) {
                Map<String, List<RsVideo>> sectionMap = chapter.getValue();
                // 章节名称
                String chapterValue = chapter.getKey();
                Set<Map.Entry<String, List<RsVideo>>> sectionEntriy = sectionMap.entrySet();
                for (Map.Entry<String, List<RsVideo>> section : sectionEntriy) {
                    // 小节名称
                    String sectionValue = section.getKey();
                    try {
                        content = URLEncoder.encode(chapterValue + " " + sectionValue + " 开始下载", "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    ps.println("curl -v http://wxpusher.zjiecode.com/api/send/message?appToken=AT_7SjHFrbcleDHq0D3hUBIzbUHABegG1Zw\\&content="+ content +"\\&uid=UID_H6M8nBUuz66NNJOZkndpP8qyKtsR");
                    // 创建目录
                    ps.println("mkdir -p " + savePath + "/" + chapterValue + "/" + sectionValue);
                    List<RsVideo> values = section.getValue();
                    int videoNum = 1;
                    for (RsVideo rsVideo : values) {
                        if(videoNum < 10){
                            rsVideo.setVideoName("0" + (videoNum++) + "_" + rsVideo.getVideoName());
                        }else{
                            rsVideo.setVideoName((videoNum++) + "_" + rsVideo.getVideoName());
                        }
                        // 输出
                        ps.println("ffmpeg -i " + rsVideo.getVideoM3u8() + " " + savePath + "/" +  chapterValue + "/" +  sectionValue + "/" + rsVideo.getVideoName() + ".mp4 > " + savePath + "/temp.log");
                    }
                    try {
                        content = URLEncoder.encode(chapterValue + " " + sectionValue + " 已下载完成", "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    ps.println("curl -v http://wxpusher.zjiecode.com/api/send/message?appToken=AT_7SjHFrbcleDHq0D3hUBIzbUHABegG1Zw\\&content="+ content +"\\&uid=UID_H6M8nBUuz66NNJOZkndpP8qyKtsR");
                }
                // 自动上传
                ps.println("nohup ./upload.sh "+ chapterValue +" >> upload.log 2>&1 &");
                try {
                    content = URLEncoder.encode(chapterValue + " 已执行上传", "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                ps.println("curl -v http://wxpusher.zjiecode.com/api/send/message?appToken=AT_7SjHFrbcleDHq0D3hUBIzbUHABegG1Zw\\&content="+ content +"\\&uid=UID_H6M8nBUuz66NNJOZkndpP8qyKtsR");
            }
            // 释放输出流
            try {
                ps.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{

            // TODO : 生成下载文件脚本
            // 创建文件
            String savePath = appConfig.getFileSavePath();
            String saveDirName = appConfig.getFileSaveDirName();
            System.out.println("savePath: " + savePath);
            System.out.println("saveDirName: " + saveDirName);
            String saveFileName = "new_file_chapter_";
            for (Integer integer : queryChapterList) {
                saveFileName += integer.toString()+"_";
            }
            saveFileName += ".sh";

            File dir = new File(savePath + File.separator + saveDirName);
            if( !dir.exists() ){
                dir.mkdirs();
            }
            File saveFile = new File(dir, saveFileName);
            if( !saveFile.exists() ){
                try {
                    saveFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            savePath = "/usr/local/baiduCloud";
            // 封装集合
            Map<String, Map<String, List<RsFile>>> map = new HashMap<>();
            for (Integer chaId : queryChapterList) {
                // 添加章节Map
                Map<String, List<RsFile>> chaMap = new HashMap<>();
                map.put(chapterArr[chaId-1], chaMap);
                List<String> strings = rsFileMapper.querySection(chaId);
                // 小节编号
                int sectionNum = 1;
                for (String string : strings) {
                    // 章节Map里添加小节Map
                    List<RsFile> secMap = new ArrayList<>();
                    String string2 = string.trim().replaceAll(" ", "_").replaceAll("\\(", "_").replaceAll("\\)", "").replaceAll("&", "和");
                    chaMap.put("第"+(sectionNum++)+"节_"+string2, secMap);
                    // 小节里查询file
                    RsFileExample rsFileExample = new RsFileExample();
                    RsFileExample.Criteria criteria = rsFileExample.createCriteria();
                    criteria.andChaIdEqualTo(chaId);
                    criteria.andSectionTitleEqualTo(string);
                    List<RsFile> rsFiles = rsFileMapper.selectByExample(rsFileExample);
                    for (RsFile rsFile : rsFiles) {
                        // 查询fileUrl
                        FileUrlExample fileUrlExample = new FileUrlExample();
                        FileUrlExample.Criteria criteria1 = fileUrlExample.createCriteria();
                        criteria1.andRsFileIdEqualTo(rsFile.getFileId());
                        List<FileUrl> fileUrls = fileUrlMapper.selectByExample(fileUrlExample);
                        rsFile.setFileUrlList(fileUrls);
                    }
                    // 添加到小节Map
                    secMap.addAll(rsFiles);
                }
            }
            String msg = null;
            // 创建输出流
            FileOutputStream fileOutputStream = null;
            PrintStream ps = null;
            try {
                fileOutputStream = new FileOutputStream(saveFile);
                ps = new PrintStream(fileOutputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 遍历集合
            Set<Map.Entry<String, Map<String, List<RsFile>>>> chapterEntry = map.entrySet();
            for (Map.Entry<String, Map<String, List<RsFile>>> chapter : chapterEntry) {
                Map<String, List<RsFile>> sectionMap = chapter.getValue();
                // 章节名称
                String chapterValue = chapter.getKey();
                Set<Map.Entry<String, List<RsFile>>> sectionEntriy = sectionMap.entrySet();
                // 章节文件上传开始下载
                try {
                    msg = URLEncoder.encode(chapterValue + " 资料文件开始下载...", "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                ps.println("curl -v http://wxpusher.zjiecode.com/api/send/message?appToken=AT_7SjHFrbcleDHq0D3hUBIzbUHABegG1Zw\\&content="+ msg +"\\&uid=UID_H6M8nBUuz66NNJOZkndpP8qyKtsR");
                for (Map.Entry<String, List<RsFile>> section : sectionEntriy) {
                    // 小节名称
                    String sectionValue = section.getKey();
                    List<RsFile> rsFiles = section.getValue();
                    for (RsFile rsFile : rsFiles) {
                        // 创建目录
                        ps.println("mkdir -p \"" + savePath + "/新职课-JavaEE开发工程师-V3.1/" + chapterValue + "/" + sectionValue + "/资料_" + rsFile.getFileName() + "\"");
                        // 输出
                        List<FileUrl> fileUrlList = rsFile.getFileUrlList();
                        for (FileUrl fileUrl : fileUrlList) {
                            ps.println("nohup wget -O \"" + savePath + "/新职课-JavaEE开发工程师-V3.1/" +  chapterValue + "/" +  sectionValue + "/资料_" + rsFile.getFileName() + "/" + fileUrl.getFileName() + "\" " + fileUrl.getFileUrl() + " > wget.log 2>&1 &");
                        }
                    }
                    // 小节文件下载完成
                    try {
                        msg = URLEncoder.encode(chapterValue + " " + sectionValue + " 资料文件已下载完成", "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    ps.println("curl -v http://wxpusher.zjiecode.com/api/send/message?appToken=AT_7SjHFrbcleDHq0D3hUBIzbUHABegG1Zw\\&content="+ msg +"\\&uid=UID_H6M8nBUuz66NNJOZkndpP8qyKtsR");
                }
//                // 自动上传
//                ps.println("sleep 5");
//                ps.println("nohup ./upload.sh "+ chapterValue +" >> upload.log 2>&1 &");
//                ps.println("sleep 5");
                // 章节文件上传已执行
                try {
                    msg = URLEncoder.encode(chapterValue + " 资料文件下载完成", "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                ps.println("sleep 3");
                ps.println("curl -v http://wxpusher.zjiecode.com/api/send/message?appToken=AT_7SjHFrbcleDHq0D3hUBIzbUHABegG1Zw\\&content="+ msg +"\\&uid=UID_H6M8nBUuz66NNJOZkndpP8qyKtsR");
                ps.println("sleep 3");
            }
            // 释放输出流
            try {
                ps.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
